from django.http import HttpResponse, JsonResponse
from rest_framework import mixins
from rest_framework.authentication import TokenAuthentication
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from apps.user.models import User, UserAddress
from apps.user.serializers import UserSerializer, UserAddressSerializer
from utils import ResponseMessage
from utils.ResponseMessage import UserResponse
from utils.jwt import create_token, JWTURLParamAuthentication, JWTHeaderAuthentication
from utils.password_encode import get_md5

# 用户注册
class UserView(APIView):
    def post(self, request, *args, **kwargs):
        # 反序列化
        data = request.data
        print(data)
        user_ser = UserSerializer(data=data)
        # print(type(user_ser))  # 'apps.user.serializers.UserSerializer'
        if user_ser.is_valid(raise_exception=True):
            user = user_ser.save()
            print(user)
            print("成功")
            # print(type(user))  # 'apps.user.models.User'
            # 序列化
            user_json_data = UserSerializer(instance=user)
            print(user_json_data.data) # {'user_id': 41, 'gender_text': '男', 'name': '叫我DPT', 'email': '4659753100@QQ.com', 'mobile': '13191273507', 'create_time': '2024-04-01T03:23:21.037525Z'}
            return UserResponse.success(user_json_data.data)
        else:
            print(user_ser.errors)
            return HttpResponse(user_ser.errors)

    def get(self, request, *args, **kwargs):
        email = request.GET.get('email')
        user = User.objects.get(email=email)
        user_json_data = UserSerializer(instance=user)
        return UserResponse.success(user_json_data.data)

class UserAddressView(GenericAPIView,
                      mixins.CreateModelMixin,
                      mixins.RetrieveModelMixin,
                      mixins.UpdateModelMixin,
                      mixins.DestroyModelMixin):
    serializer_class = UserAddressSerializer
    queryset = UserAddress.objects
    authentication_classes = [JWTHeaderAuthentication,]

    def get_queryset(self):
        # 确保返回标准的Django QuerySet
        return UserAddress.objects.all()
    # self.get_queryset

    def post(self, request):
        # if not request.user.get("status"):
        #     return JsonResponse(request.user, safe=False)
        # print(request.user)
        # email = request.user.get("data").get("username")
        email = '001@QQ.com'
        request_data = request.data
        print(request_data)
        if request_data['default'] == True:
            self.get_queryset().filter(email=email).update(default=0)
            request_data['default'] = 1
        else:
            request_data['default'] = 0
        request_data['email'] = email
        self.get_queryset().create(**request_data)
        return ResponseMessage.AddressResponse.success("用户地址添加成功")
        # return self.create(request)

    def get(self, request):
        # if not request.user.get("status"):
        #     return JsonResponse(request.user, safe=False)
        # print(request.user)
        # email = request.user.get("data").get("username")
        email = '001@QQ.com'
        db_data = self.get_queryset().filter(email=email).all().order_by('-default')
        ser_data = self.get_serializer(instance=db_data,many=True).data
        return ResponseMessage.AddressResponse.success(ser_data)
        # return self.retrieve(request)
            # return ResponseMessage.UserResponse.success(request.user)

    def put(self, request, pk):
        if not request.user['status']:
            return ResponseMessage.UserResponse.failed(request.user)
        else:
            return self.update(request, pk)

    def delete(self, request, pk):
        if not request.user['status']:
            return ResponseMessage.UserResponse.failed(request.user)
        else:
            return self.destroy(request,pk)

class UserAddressListView(GenericAPIView, mixins.ListModelMixin):
    serializer_class = UserAddressSerializer
    queryset = UserAddress.objects
    authentication_classes = [JWTURLParamAuthentication,]

    def get(self, request):
        # print(request.user) # 对应的是JWTAuthentication的第一个返回值token_data
        # print(request.auth) # 对应的是JWTAuthentication的第二个返回值token
        # 将验证Token状态的逻辑放在视图类的好处是：当你在类中加入了authentication_classes后，如果有不需要验证的类，就不加验证的代码，就可以跳过验证进行相应
        if not request.user['status']:
            return ResponseMessage.UserResponse.failed(request.user)
        else:
            return ResponseMessage.UserResponse.success(request.user)

        # return self.list(request)

# 用户登录
class UserLoginView(GenericAPIView):
    serializer_class = UserSerializer
    queryset = User.objects

    def post(self, request):
        data = request.data
        # print(data)
        email = data['name']
        # print(email)
        user = User.objects.filter(email=email).first()
        print(user)
        if not user:
            return ResponseMessage.UserResponse.other('用户名不存在或者密码错误')
        else:
            password = data['password']
            form_password = get_md5(password)
            db_password = user.password
            if form_password != db_password:
                return ResponseMessage.UserResponse.other('用户名不存在或者密码错误')
            else:
                token_payload = {
                    'email': user.email,
                }
                token_data = create_token(token_payload, timeout=1)
                result = {
                    'token': token_data,
                    'name': user.name,
                    'status': '登陆成功'
                }
                return ResponseMessage.UserResponse.success(result)